package com.rsa;

import java.io.FileWriter;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

/**
 * @author zhanghuibo
 * @version 1.0.0
 * @package com.rsa
 * @className RSASample
 * @date 2024-12-25  17:21
 */
public class RSASample {

    public static void main(String[] args) {
        try {
            KeyPair keyPair = generateKeyPair(2048);
            String privateKeyString = encodePrivateKeyToPEM(keyPair.getPrivate());
            String publicKeyString = encodePublicKeyToPEM(keyPair.getPublic());

            // 打印密钥（或将其保存到文件、数据库等）
            System.out.println("Private Key:\n" + privateKeyString);
            System.out.println("Public Key:\n" + publicKeyString);

            // 保存到文件（可选）
            saveToFile("private_key.pem", privateKeyString);
            saveToFile("public_key.pem", publicKeyString);

        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
    }

    public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize);
        return keyGen.generateKeyPair();
    }

    public static String encodePrivateKeyToPEM(PrivateKey privateKey) {
        return "-----BEGIN PRIVATE KEY-----\n" +
                Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(((RSAPrivateKey) privateKey).getEncoded()) +
                "\n-----END PRIVATE KEY-----";
    }

    public static String encodePublicKeyToPEM(PublicKey publicKey) {
        return "-----BEGIN PUBLIC KEY-----\n" +
                Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(((RSAPublicKey) publicKey).getEncoded()) +
                "\n-----END PUBLIC KEY-----";
    }

    public static void saveToFile(String fileName, String content) throws IOException {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
        }
    }

}
